//
//  ShoppingGoodsContentViewController.m
//  quxiangtao
//
//  Created by xbmios on 2018/7/24.
//  Copyright © 2018年 shanhaijin. All rights reserved.
//

#import "ShoppingGoodsContentViewController.h"
#import "GoodsPicView.h"
#import "GoodPriceView.h"
#import "MemberView.h"
#import "GoodsTitleView.h"
#import "GoodsSelectedView.h"
#import "RecommendHotView.h"
#import "GoodsDetailContentView.h"
#import "BootomBtnView.h"

#import <UMShare/UMShare.h>
#import <UShareUI/UShareUI.h>

#import <WebKit/WebKit.h>

@interface ShoppingGoodsContentViewController ()<SDCycleScrollViewDelegate, UIScrollViewDelegate, WKUIDelegate, WKNavigationDelegate>

@property (strong, nonatomic) UIView *navBgView;

@property (strong, nonatomic) UIScrollView *contentScrollView;

@property (strong, nonatomic) GoodsPicView *goodsPicView;
@property (strong, nonatomic) GoodPriceView *priceView;
@property (strong, nonatomic) MemberView *memberV;
@property (strong, nonatomic) GoodsTitleView *titleView;
@property (strong, nonatomic) GoodsSelectedView *selectedView;
@property (strong, nonatomic) RecommendHotView *recommendHotView;
//@property (strong, nonatomic) GoodsDetailContentView *goodsDetailView;

@property (strong, nonatomic) UIView *goodsDetailView;
@property (strong, nonatomic) WKWebView *webView;

@property (strong, nonatomic) BootomBtnView *BtnView;

@property (strong, nonatomic) NSArray *goodsSelectedArr;

// 导航栏白色背景的透明度
@property (assign, nonatomic) CGFloat alpha;

// 详情页数据
@property (strong, nonatomic) NSDictionary *contentDict;

@property (strong, nonatomic) UIView *tileV;

@property (nonatomic, strong) NSString *loadString;

@end

@implementation ShoppingGoodsContentViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = WhiteColor;
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    // 导航栏右侧按钮
    [self createRightBarButtonItems];

    [self createUI];
    [self createTopSameUI];
    [self createDifferenceUI];
    [self createRemainUI];
    
    self.recommendHotView.hidden = YES;
    
    __weak typeof(self) weakSelf = self;
    [self.recommendHotView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(0);
        make.top.mas_equalTo(weakSelf.selectedView.mas_bottom).with.offset(jisuan(0));
    }];
    
    [self.view layoutIfNeeded];
    CGFloat height = CGRectGetMaxY(self.webView.frame) + jisuan(20);
    self.contentScrollView.contentSize = CGSizeMake(0, height);

}


- (void)loadData {
    
    NSString *str = [NSString stringWithFormat:@"{\"sid\" : \"%@\", \"userid\" : \"%@\"}", [RSA encryptString:self.goodID publicKey:PublicKey], [RSA encryptString:[CommonUserInfo sharedInstance].user_id publicKey:PublicKey]];
    
    [PPNetworkHelper POST:@"goods/Qxtgoods/getGoods" parameters:@{@"json" : str} success:^(id responseObject) {
        WS(weakSelf);
        NSLog(@"自营商品详情页%@",responseObject);
        
        if ([responseObject[@"code"] integerValue] == 1) {
            
            NSDictionary *dict = responseObject[@"data"];
            self.contentDict = dict;
            [TalkingData onViewItem:weakSelf.goodID category:@"自营商品" name:dict[@"title"] unitPrice:[dict[@"sale_price"] floatValue] * 100];
            [self loadGoodDetailWithStr:dict[@"content"]];
            self.goodsPicView.imageArr = dict[@"goods_pic"];
            self.priceView.contentDict = dict;
            self.titleView.titleStr = dict[@"title"];
            self.selectedView.contentDict = dict;
            
//            self.goodsDetailView.contentStr = dict[@"content"];
            
            self.BtnView.contentDict = dict;
   
        }else {
            
            [[KYAlertView sharedInstance] showAlertViewWithMessage:responseObject[@"msg"]];
        }
        
    } failure:^(NSError *error) {
        
    
    }];
    
}

#pragma mark -收藏
- (void)storeUpBtnClick:(UIButton *)btn {
    
    NSLog(@"收藏");
    
}

#pragma mark -分享
- (void)shareBtnClick:(UIButton *)btn {
    
    NSLog(@"分享");

}

#pragma mark -标题点击
- (void)lableClick:(UIGestureRecognizer *)recognizer {
    
    UILabel *label = (UILabel *)recognizer.view;

    for (int i = 0; i < self.tileV.subviews.count; i ++) {

        UILabel *temp = self.tileV.subviews[i];
        temp.textColor = Color333333;
        temp.backgroundColor = WhiteColor;
        
    }

    label.textColor = WhiteColor;
    label.backgroundColor = Color333333;
    
    if (label.tag == 0) {
        
        [self loadGoodDetailWithStr:self.contentDict[@"content"]];
    }else {
        [self loadGoodDetailWithStr:self.contentDict[@"parameters"]];
    }
    
}

- (void)loadGoodDetailWithStr:(NSString *)contentStr {
    self.loadString = contentStr;
    NSString *str = [NSString stringWithFormat:@"%@",contentStr];
    str = [str stringByReplacingOccurrencesOfString:@"\\\"" withString:@"\""];
    str = [str stringByReplacingOccurrencesOfString:@"\\/" withString:@"/"];
    str = [str stringByReplacingOccurrencesOfString:@"\\n" withString:@""];
    str = [str stringByReplacingOccurrencesOfString:@"\\t" withString:@""];
    str = [str stringByReplacingOccurrencesOfString:@"\"" withString:@""];
    str = [str stringByReplacingOccurrencesOfString:@"\\r" withString:@""];
    
    
    
    [self.webView loadHTMLString:str baseURL:nil];

}

- (void)createTopSameUI {
    
    __weak typeof(self) weakSelf = self;
    
    self.goodsPicView = [[GoodsPicView alloc] init];
    [self.contentScrollView addSubview:self.goodsPicView];
    
    self.priceView = [[GoodPriceView alloc] initType:0];
    [self.contentScrollView addSubview:self.priceView];
    
    [self.goodsPicView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_equalTo(weakSelf.view.mas_left);
        make.right.mas_equalTo(weakSelf.view.mas_right);
        make.top.mas_equalTo(weakSelf.contentScrollView.mas_top);
        make.height.mas_equalTo(jisuan(750));
        
    }];
    
    [self.priceView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_equalTo(weakSelf.view.mas_left);
        make.right.mas_equalTo(weakSelf.view.mas_right);
        make.top.mas_equalTo(weakSelf.goodsPicView.mas_bottom).with.offset(jisuan(1));
        make.height.mas_equalTo(jisuan(150));
        
    }];
    
}

- (void)createDifferenceUI {
    
    __weak typeof(self) weakSelf = self;
    
    self.memberV = [[MemberView alloc] init];
    self.memberV.parentVC = self;
    [self.contentScrollView addSubview:self.memberV];
    
    self.titleView = [[GoodsTitleView alloc] init];
//    self.titleView.titleStr = @"GUCCI 古驰 女士Ace休闲真皮镶钻版小白鞋一箭穿心图案";

    self.titleView.heigt = ^(CGFloat height) {
        
        [weakSelf.titleView mas_updateConstraints:^(MASConstraintMaker *make) {
            
            make.height.mas_equalTo(height);
        }];
        
        
    };
    
    [self.contentScrollView addSubview:self.titleView];
    
    if ([[CommonUserInfo sharedInstance].VIPLevel integerValue] != 10) {
        // 未达到会员最高等级
        self.memberV.hidden = NO;
        
        [self.memberV mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.left.mas_equalTo(weakSelf.view.mas_left);
            make.right.mas_equalTo(weakSelf.view.mas_right);
            make.top.mas_equalTo(weakSelf.priceView.mas_bottom);
            make.height.mas_equalTo(jisuan(100));
            
        }];
        [self.titleView mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.left.mas_equalTo(weakSelf.view.mas_left);
            make.right.mas_equalTo(weakSelf.view.mas_right);
            make.top.mas_equalTo(weakSelf.priceView.mas_bottom).with.offset(jisuan(100));
            make.height.mas_equalTo(jisuan(170));
        }];
        
    }else {
        
        // 已达到会员最高等级 隐藏不创建
        
        self.memberV.hidden = YES;
        
        [self.titleView mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.left.mas_equalTo(weakSelf.view.mas_left);
            make.right.mas_equalTo(weakSelf.view.mas_right);
            make.top.mas_equalTo(weakSelf.priceView.mas_bottom);
            make.height.mas_equalTo(jisuan(170));
        }];
        
    }
    
}

- (void)createRemainUI {
    
    __weak typeof(self) weakSelf = self;

    self.selectedView = [[GoodsSelectedView alloc] initWithType:0 andArray:self.goodsSelectedArr];
    self.selectedView.parentVC = self;
    [self.contentScrollView addSubview:self.selectedView];

    self.recommendHotView = [[RecommendHotView alloc] init];
    [self.contentScrollView addSubview:self.recommendHotView];

    self.goodsDetailView = [[UIView alloc] init];
    self.goodsDetailView.backgroundColor = WhiteColor;
    [self.contentScrollView addSubview:self.goodsDetailView];
    [self createTitleView];
    
    [self.contentScrollView addSubview:self.webView];

    [self.selectedView mas_makeConstraints:^(MASConstraintMaker *make) {

        make.left.mas_equalTo(weakSelf.view.mas_left);
        make.right.mas_equalTo(weakSelf.view.mas_right);
        make.top.mas_equalTo(weakSelf.titleView.mas_bottom).with.offset(jisuan(20));
        make.height.mas_equalTo(jisuan(320));
    }];
    
    [self.recommendHotView mas_makeConstraints:^(MASConstraintMaker *make) {

        make.left.mas_equalTo(weakSelf.view.mas_left);
        make.right.mas_equalTo(weakSelf.view.mas_right);
        make.top.mas_equalTo(weakSelf.selectedView.mas_bottom).with.offset(jisuan(20));
        make.height.mas_equalTo(jisuan(934));
    }];
    [self.goodsDetailView mas_makeConstraints:^(MASConstraintMaker *make) {

        make.left.mas_equalTo(weakSelf.view.mas_left);
        make.right.mas_equalTo(weakSelf.view.mas_right);
        make.top.mas_equalTo(weakSelf.recommendHotView.mas_bottom).with.offset(jisuan(20));
        make.height.mas_equalTo(jisuan(90));
    }];

    [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_equalTo(weakSelf.view.mas_left);
        make.right.mas_equalTo(weakSelf.view.mas_right);
        make.top.mas_equalTo(weakSelf.goodsDetailView.mas_bottom);
        make.height.mas_equalTo(jisuan(20));
    }];
    
}

- (void)createTitleView {
    
    NSArray *array = @[@"图文详情", @"规格参数"];
    CGFloat width = (WIDTH - jisuan(20) * 2) / 2.0;
    
    UIView *tileV = [[UIView alloc] init];
    self.tileV = tileV;
    tileV.frame = CGRectMake(jisuan(20), jisuan(10), WIDTH - 2 * jisuan(20), jisuan(80));
    [self.goodsDetailView addSubview:tileV];
    
    for (int i = 0; i < 2; i ++) {
        
        UILabel *label = [[UILabel alloc] init];
        label.userInteractionEnabled = YES;
        label.font = Font(30);
        label.tag = i;
        label.textAlignment = NSTextAlignmentCenter;
        label.text = array[i];
        label.layer.borderWidth = jisuan(2);
        label.layer.borderColor = Color333333.CGColor;
        
        if (i == 0) {
            
            label.backgroundColor = Color333333;
            label.textColor = WhiteColor;
            
        }else {
            
            label.backgroundColor = WhiteColor;
            label.textColor = Color333333;
            
        }
        
        label.frame = CGRectMake(width * i, 0, width, jisuan(80));
        [tileV addSubview:label];
        
        UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(lableClick:)];
        [label addGestureRecognizer:recognizer];
    
    }
    
}

- (void)createUI {
    
    __weak typeof(self) weakSelf = self;
    [self.view addSubview:self.contentScrollView];

    self.BtnView = [[BootomBtnView alloc] initWithType:0];
    self.BtnView.parentVC = self;
    [self.view addSubview:self.BtnView];

    [self.BtnView mas_makeConstraints:^(MASConstraintMaker *make) {

        make.left.mas_equalTo(weakSelf.view.mas_left);
        make.right.mas_equalTo(weakSelf.view.mas_right);
        make.bottom.mas_equalTo(weakSelf.view.mas_bottom);
        make.height.mas_equalTo(jisuan(100));
    }];

    [self.contentScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_equalTo(weakSelf.view.mas_left);
        make.right.mas_equalTo(weakSelf.view.mas_right);
        make.top.mas_equalTo(weakSelf.view.mas_top);
        make.bottom.mas_equalTo(weakSelf.BtnView.mas_top);
        
    }];
    
}

- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
    
    WKNavigationResponsePolicy actionPolicy = WKNavigationResponsePolicyAllow;
    //这句是必须加上的，不然会异常
    decisionHandler(actionPolicy);
    
}

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    
    WKNavigationActionPolicy actionPolicy = WKNavigationActionPolicyAllow;
    
    decisionHandler(actionPolicy);
    
}

/// 2 页面开始加载
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    
    
}

/// 4 开始获取到网页内容时返回
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation {
    
    
}

/// 5 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {

    // document.body.scrollHeight   clientHeight    offsetHeight
    
    [webView evaluateJavaScript:@"document.body.scrollHeight" completionHandler:^(id _Nullable finishHeight, NSError * _Nullable error) {
        WS(weakSelf);
        CGFloat newHeight = weakSelf.loadString.length > 0 ?  [finishHeight floatValue] : jisuan(20);
        [weakSelf.webView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(newHeight);
        }];
        [weakSelf.view layoutIfNeeded];
        CGFloat height = CGRectGetMaxY(weakSelf.goodsDetailView.frame) + newHeight;
        weakSelf.contentScrollView.contentSize = CGSizeMake(0, height);

    }];
    
}

#pragma mark -scrollviewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
   
    CGFloat alpha = scrollView.contentOffset.y / 300;
    
    self.alpha = alpha;
    
    if (alpha > 1) {
    
        alpha = 1;
        
    }
    
    if (scrollView == self.contentScrollView) {
        
        self.navBgView.backgroundColor = WhiteColor;
        self.navBgView.alpha = alpha;
        
    }
    
}

#pragma mark -导航栏右侧按钮
- (void)createRightBarButtonItems {
    
    UIButton *storeUpBtn = [[UIButton alloc] init];
    [storeUpBtn setImage:[UIImage imageNamed:@"navStoreUpBG"] forState:UIControlStateNormal];
    [storeUpBtn setImage:[UIImage imageNamed:@"navStoreUpBG"] forState:UIControlStateSelected];
    [storeUpBtn addTarget:self action:@selector(storeUpBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [storeUpBtn sizeToFit];
    UIBarButtonItem *storeUpItem = [[UIBarButtonItem alloc] initWithCustomView:storeUpBtn];
    
    UIButton *shareBtn = [[UIButton alloc] init];
    [shareBtn setImage:[UIImage imageNamed:@"navShareBG"] forState:UIControlStateNormal];
    [shareBtn setImage:[UIImage imageNamed:@"navShareBG"] forState:UIControlStateSelected];
    [shareBtn sizeToFit];
    [shareBtn addTarget:self action:@selector(shareBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *shareItem = [[UIBarButtonItem alloc] initWithCustomView:shareBtn];
    
    UIBarButtonItem* fixedSpaceBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    fixedSpaceBarButtonItem.width = jisuan(44);
    
    self.navigationItem.rightBarButtonItems = @[shareItem, fixedSpaceBarButtonItem,storeUpItem];

}

#pragma mark -lazy
- (UIScrollView *)contentScrollView {
    
    if (!_contentScrollView) {
        
        _contentScrollView = [[UIScrollView alloc] init];
        _contentScrollView.backgroundColor = Colorf2f2f2;
        
        _contentScrollView.showsVerticalScrollIndicator = NO;
        _contentScrollView.showsHorizontalScrollIndicator = NO;
        
        _contentScrollView.delegate = self;
        
        if (@available (iOS 11.0 , *)) {
            
            _contentScrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        
    }
    
    return _contentScrollView;
}

- (NSArray *)goodsSelectedArr {
    
    if (!_goodsSelectedArr) {
        
        _goodsSelectedArr = @[
                              @{
                                  
                                  @"title" : @"选择",
                                  @"des"   : @"颜色、尺寸",
                                  
                                  },
                              @{
                                  
                                  @"title" : @"配送",
                                  @"des"   : @"至北京市丰台区花乡京明商务楼A座4001",
                                  
                                  },
                              @{
                                  
                                  @"title" : @"运费",
                                  @"des"   : @"包邮",
                                  
                                  },
                              @{
                                  
                                  @"title" : @"说明",
                                  @"des"   : @"不支持7天无理由退换",
                                  
                                  },
                              
                              ];
        
    }
    
    return _goodsSelectedArr;
}

- (UIView*)navBgView {
    
    if (!_navBgView) {
        _navBgView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.navigationController.navigationBar.frame.size.width, self.navigationController.navigationBar.frame.size.height + Height_StatusBar)];
        [self.navigationController.view insertSubview:_navBgView belowSubview:self.navigationController.navigationBar];
    }
    return _navBgView;
    
}

- (WKWebView *)webView {
    
    if (!_webView) {
        NSString *jScript = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta); var imgs = document.getElementsByTagName('img');for (var i in imgs){imgs[i].style.maxWidth='100%';imgs[i].style.height='auto';}";

        WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
        WKUserContentController *wkUController = [[WKUserContentController alloc] init];
        [wkUController addUserScript:wkUScript];
        WKWebViewConfiguration *wkWebConfig = [[WKWebViewConfiguration alloc] init];
        wkWebConfig.userContentController = wkUController;
        _webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:wkWebConfig];
        _webView.UIDelegate = self;
        _webView.navigationDelegate = self;
        _webView.backgroundColor = WhiteColor;
        _webView.scrollView.scrollEnabled = NO;
        _webView.scrollView.showsVerticalScrollIndicator = NO;
        _webView.scrollView.showsHorizontalScrollIndicator = NO;
        
        if (@available(iOS 11.0 , *)) {
            
            _webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            
        }
        
    }
    
    return _webView;
}

#pragma mark -设置
- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    [self loadData];
    
    self.navigationController.navigationBar.hidden = NO;
    
    UIImage *image = [[UIImage alloc] init];
    [self.navigationController.navigationBar setBackgroundImage:image forBarMetrics:UIBarMetricsCompact];
    [self.navigationController.navigationBar setShadowImage:image];
    self.navigationController.navigationBar.translucent = YES;
    self.navBgView.alpha = self.alpha;
    [TalkingData trackPageBegin:@"自营商品详情页"];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [TalkingData trackPageEnd:@"自营商品详情页"];
}

- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


@end
